package top.jfunc.token.mem;

import top.jfunc.token.CaptchaManger;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 基于内存的验证码管理器，只适合单机
 * @author xiongshiyan at 2018/10/8 , contact me with email yanshixiong@126.com or phone 15208384257
 */
public abstract class BaseMemoryCaptchaManager<M> implements CaptchaManger<M> {
    private Map<Object,Object> map = new ConcurrentHashMap<>();
    /**
     * 以秒为单位的过期时间
     */
    protected long expires  = 1800;

    @Override
    public void updateCaptcha(M member, String captcha) {
        /// TODO 对过期时间的处理
        //redisTemplate.opsForValue().set(key(member) , captcha , 1800, TimeUnit.SECONDS);
        map.put(key(member) , captcha);
    }

    @Override
    public boolean verifyCaptcha(M member, String captcha) {
        String cap = (String) map.get(key(member));
        return null != cap && cap.equalsIgnoreCase(captcha);
    }

    @Override
    public void deleteCaptcha(M member) {
        map.remove(key(member));
    }

    /**
     * 根据m获取key
     * @param member 实体
     */
    protected abstract String key(M member);

    public long getExpires() {
        return expires;
    }

    public void setExpires(long expires) {
        this.expires = expires;
    }
}
